<?php

namespace app\api\library;

use PHPMailer\PHPMailer\PHPMailer;
use think\Env;
class Email
{
    /**
     * Notes: 发送邮箱验证码
     * User: 浪子膏
     * Date: 2023/10/9 17:26
     * @param $toEmail
     * @return bool
     * @throws \PHPMailer\PHPMailer\Exception
     */
    function sendVerificationCode($toEmail): array
    {
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->CharSet = "UTF-8";                     //设定邮件编码
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'ssl';
        $mail->Host = 'smtp.qq.com';
        $mail->Port = 465;
        $mail->Username = Env::get('email.username');
        $mail->Password = Env::get('email.password');
        $mail->SetFrom(Env::get('email.username'), Env::get('email.name'));
        $mail->addAddress($toEmail);
        $mail->Subject = 'Verification Code';
        $verificationCode = $this->generateVerificationCode(); // 生成验证码
        $mail->Body = 'Your verification code is: ' . $verificationCode;
        if (!$mail->send()) {
            return ['code' => 100, 'msg' => 'Mailer Error: ' . $mail->ErrorInfo];
        } else {
            return ['code' => 200, 'email_code' => $verificationCode];
        }
    }

    /**
     * Notes: 获取随机邮箱验证码
     * User: 浪子膏
     * Date: 2023/10/9 17:26
     * @return string
     */
    function generateVerificationCode(): string
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $verificationCode = '';
        $length = 6;

        for ($i = 0; $i < $length; $i++) {
            $verificationCode .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $verificationCode;
    }
}